/**
 * 根据身份证号计算年龄
 * @param idCard 18位或15位身份证号码
 * @param asOf   截至日期，默认今天
 * @returns 年龄（整数），非法输入返回 null
 */
export function getAgeByIdCard(
  idCard: string,
  asOf: Date = new Date(),
): number | null {
  if (!idCard || (idCard.length !== 18 && idCard.length !== 15)) return null;

  let birthStr = '';
  if (idCard.length === 18) {
    birthStr = idCard.slice(6, 14); // YYYYMMDD
  } else if (idCard.length === 15) {
    birthStr = '19' + idCard.slice(6, 12); // YYMMDD 补上 19
  }

  const year = parseInt(birthStr.slice(0, 4));
  const month = parseInt(birthStr.slice(4, 6));
  const day = parseInt(birthStr.slice(6, 8));

  if (!year || !month || !day) return null;

  const birthDate = new Date(year, month - 1, day);
  if (isNaN(birthDate.getTime())) return null;

  const today = new Date(asOf.getFullYear(), asOf.getMonth(), asOf.getDate());

  let age = today.getFullYear() - birthDate.getFullYear();
  const hasBirthdayPassed =
    today.getMonth() > birthDate.getMonth() ||
    (today.getMonth() === birthDate.getMonth() &&
      today.getDate() >= birthDate.getDate());

  if (!hasBirthdayPassed) age--;

  return age < 0 ? null : age;
}
